package com.wanjia.estate.service;

import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

//打包压缩
@Service
public class CompressFolderService {
    public void compressFolder(File folder, ZipOutputStream zos, String parentDir)
            throws IOException {
        for (File file : folder.listFiles()) {
            if (file.isDirectory()) {
                // 如果是子目录，则递归调用compressFolder方法
                compressFolder(file, zos, parentDir + file.getName() + "/");
            } else {
                // 如果是文件，则创建一个ZipEntry对象，并将其加入到ZipOutputStream中
                ZipEntry ze = new ZipEntry(parentDir + file.getName());
                zos.putNextEntry(ze);

                // 将文件内容写入ZipOutputStream中
                FileInputStream fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                fis.close();

                // 完成当前ZipEntry的写入操作
                zos.closeEntry();
            }
        }
    }
}
